<template>
  <div class="dashboard-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">校园数据概览</h1>
      <div class="last-update">
        最后更新: {{ lastUpdateTime }}
        <el-button type="text" @click="refreshAllData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>
    
    <!-- 关键指标卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>学生总数</span>
          </div>
        </template>
        <div class="card-content">
          <div class="stat-number">{{ totalStudents }}</div>
          <div class="stat-change" :class="{ 'text-green': studentIncrease > 0, 'text-red': studentIncrease < 0 }">
            <el-icon v-if="studentIncrease > 0"><ArrowUp /></el-icon>
            <el-icon v-else-if="studentIncrease < 0"><ArrowDown /></el-icon>
            {{ Math.abs(studentIncrease) }} 人 (较上月)
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><UserFilled /></el-icon>
            <span>教师总数</span>
          </div>
        </template>
        <div class="card-content">
          <div class="stat-number">{{ totalTeachers }}</div>
          <div class="stat-change" :class="{ 'text-green': teacherIncrease > 0, 'text-red': teacherIncrease < 0 }">
            <el-icon v-if="teacherIncrease > 0"><ArrowUp /></el-icon>
            <el-icon v-else-if="teacherIncrease < 0"><ArrowDown /></el-icon>
            {{ Math.abs(teacherIncrease) }} 人 (较上月)
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><OfficeBuilding /></el-icon>
            <span>班级总数</span>
          </div>
        </template>
        <div class="card-content">
          <div class="stat-number">{{ totalClasses }}</div>
          <div class="stat-change" :class="{ 'text-green': classIncrease > 0, 'text-red': classIncrease < 0 }">
            <el-icon v-if="classIncrease > 0"><ArrowUp /></el-icon>
            <el-icon v-else-if="classIncrease < 0"><ArrowDown /></el-icon>
            {{ Math.abs(classIncrease) }} 个 (较上月)
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><Notebook /></el-icon>
            <span>课程总数</span>
          </div>
        </template>
        <div class="card-content">
          <div class="stat-number">{{ totalCourses }}</div>
          <div class="stat-change" :class="{ 'text-green': courseIncrease > 0, 'text-red': courseIncrease < 0 }">
            <el-icon v-if="courseIncrease > 0"><ArrowUp /></el-icon>
            <el-icon v-else-if="courseIncrease < 0"><ArrowDown /></el-icon>
            {{ Math.abs(courseIncrease) }} 门 (较上月)
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <el-card shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>学生年级分布</span>
            <el-select v-model="gradeChartType" @change="updateGradeChart" size="small">
              <el-option label="按年级" value="grade" />
              <el-option label="按专业" value="major" />
              <el-option label="按学院" value="department" />
            </el-select>
          </div>
        </template>
        <div class="chart-content">
          <canvas id="gradeDistributionChart" width="400" height="250"></canvas>
        </div>
      </el-card>
      
      <el-card shadow="hover">
        <template #header>
          <div class="chart-header">
            <span>班级人数统计</span>
            <el-select v-model="classChartType" @change="updateClassChart" size="small">
              <el-option label="按班级" value="class" />
              <el-option label="按专业" value="major" />
              <el-option label="按学院" value="department" />
            </el-select>
          </div>
        </template>
        <div class="chart-content">
          <canvas id="classSizeChart" width="400" height="250"></canvas>
        </div>
      </el-card>
    </div>
    
    <!-- 数据表格区域 -->
    <div class="tables-container">
      <el-card shadow="hover">
        <template #header>
          <div class="table-header">
            <span>最新添加的学生</span>
            <el-input v-model="studentSearch" placeholder="搜索学生" size="small" @keyup.enter="searchStudents" />
            <el-button type="primary" size="small" @click="searchStudents">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
          </div>
        </template>
        <div class="table-content">
          <el-table :data="recentStudents" border stripe>
            <el-table-column prop="studentId" label="学号" width="120" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="className" label="班级" width="150" />
            <el-table-column prop="gender" label="性别" width="80" />
            <el-table-column prop="createTime" label="注册时间" width="180" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" size="small" @click="viewStudent(scope.row)">查看</el-button>
                <el-button type="text" size="small" @click="editStudent(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            @size-change="handleStudentSizeChange"
            @current-change="handleStudentPageChange"
            :current-page="studentCurrentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="studentPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="studentTotal"
          />
        </div>
      </el-card>
      
      <el-card shadow="hover">
        <template #header>
          <div class="table-header">
            <span>班级统计</span>
            <el-select v-model="classFilter" @change="filterClasses" size="small">
              <el-option label="全部年级" value="" />
              <el-option v-for="grade in grades" :key="grade" :label="grade" :value="grade" />
            </el-select>
          </div>
        </template>
        <div class="table-content">
          <el-table :data="filteredClasses" border stripe>
            <el-table-column prop="className" label="班级名称" width="150" />
            <el-table-column prop="grade" label="年级" width="80" />
            <el-table-column prop="majorName" label="专业" width="120" />
            <el-table-column prop="departmentName" label="学院" width="120" />
            <el-table-column prop="studentCount" label="学生人数" width="100" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button type="text" size="small" @click="viewClass(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            @size-change="handleClassSizeChange"
            @current-change="handleClassPageChange"
            :current-page="classCurrentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="classPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="classTotal"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, computed, watch } from 'vue';
import Chart from 'chart.js/auto';
import { 
  getStudentList,
  getStudentById,
  addStudent,
  updateStudent,
  deleteStudent
} from '@/api/student';
import { 
  getTeacherList
} from '@/api/teacher';
import { 
  getCourseList
} from '@/api/course';
import { 
  getClasssList,
  getClasssDetail
} from '@/api/classs';
import { 
  getMajorList
} from '@/api/major';
import { 
  getDepartmentList
} from '@/api/department';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  User, 
  UserFilled, 
  OfficeBuilding, 
  Notebook, 
  Refresh, 
  Search, 
  ArrowUp, 
  ArrowDown 
} from '@element-plus/icons-vue';

export default defineComponent({
  name: 'Dashboard',
  setup() {
    // 图标注册
    const icons = {
      User,
      UserFilled,
      OfficeBuilding,
      Notebook,
      Refresh,
      Search,
      ArrowUp,
      ArrowDown
    };
    
    // 状态数据
    const totalStudents = ref(0);
    const totalTeachers = ref(0);
    const totalClasses = ref(0);
    const totalCourses = ref(0);
    const studentIncrease = ref(0);
    const teacherIncrease = ref(0);
    const classIncrease = ref(0);
    const courseIncrease = ref(0);
    const lastUpdateTime = ref('');
    
    // 图表相关
    const gradeChartType = ref('grade');
    const classChartType = ref('class');
    let gradeDistributionChart = ref(null);
    let classSizeChart = ref(null);
    
    // 学生表格相关
    const recentStudents = ref([]);
    const studentCurrentPage = ref(1);
    const studentPageSize = ref(10);
    const studentTotal = ref(0);
    const studentSearch = ref('');
    
    // 班级表格相关
    const classes = ref([]);
    const filteredClasses = ref([]);
    const classCurrentPage = ref(1);
    const classPageSize = ref(10);
    const classTotal = ref(0);
    const classFilter = ref('');
    const grades = ref(['高一', '高二', '高三']);
    
    // 加载状态
    const loadingDashboard = ref(false);
    const loadingStudents = ref(false);
    const loadingClasses = ref(false);
    
    // 获取所有统计数据
    const fetchDashboardData = async () => {
      loadingDashboard.value = true;
      
      try {
        // 获取学生总数
        const studentRes = await getStudentList(1, 1, 0, {});
        if (studentRes.code === 200) {
          totalStudents.value = studentRes.data.total || 0;
          // 模拟较上月增长数据
          studentIncrease.value = Math.floor(Math.random() * 20) - 5;
        }
        
        // 获取教师总数
        const teacherRes = await getTeacherList({ pageNum: 1, pageSize: 1, orderBy: 0 });
        if (teacherRes.code === 200) {
          totalTeachers.value = teacherRes.data.total || 0;
          teacherIncrease.value = Math.floor(Math.random() * 5) - 1;
        }
        
        // 获取班级总数
        const classRes = await getClasssList(1, 1, 0, {});
        if (classRes.code === 200) {
          totalClasses.value = classRes.data.total || 0;
          classIncrease.value = Math.floor(Math.random() * 3) - 1;
        }
        
        // 获取课程总数
        const courseRes = await getCourseList(1, 1, 0, {});
        if (courseRes.code === 200) {
          totalCourses.value = courseRes.data.total || 0;
          courseIncrease.value = Math.floor(Math.random() * 5) - 1;
        }
        
        // 更新最后更新时间
        lastUpdateTime.value = new Date().toLocaleString();
        
        // 初始化图表
        initGradeDistributionChart();
        initClassSizeChart();
      } catch (error) {
        console.error('获取仪表盘数据失败:', error);
        ElMessage.error('获取数据失败，请稍后重试');
      } finally {
        loadingDashboard.value = false;
      }
    };
    
    // 初始化年级分布图表
    const initGradeDistributionChart = async () => {
      try {
        // 获取年级分布数据
        const classRes = await getClasssList(1, 100, 0, {});
        if (classRes.code !== 200 || !classRes.data.list) return;
        
        const classesData = classRes.data.list;
        
        // 销毁旧图表
        if (gradeDistributionChart.value) {
          gradeDistributionChart.value.destroy();
        }
        
        let labels, data;
        
        if (gradeChartType.value === 'grade') {
          // 按年级统计
          const gradeMap = { '高一': 0, '高二': 0, '高三': 0 };
          classesData.forEach(cls => {
            if (gradeMap[cls.grade]) {
              gradeMap[cls.grade] += cls.studentCount || 0;
            }
          });
          labels = Object.keys(gradeMap);
          data = Object.values(gradeMap);
        } else if (gradeChartType.value === 'major') {
          // 按专业统计
          const majorMap = {};
          classesData.forEach(cls => {
            if (!majorMap[cls.majorName]) {
              majorMap[cls.majorName] = 0;
            }
            majorMap[cls.majorName] += cls.studentCount || 0;
          });
          labels = Object.keys(majorMap);
          data = Object.values(majorMap);
        } else {
          // 按学院统计
          const departmentMap = {};
          classesData.forEach(cls => {
            if (!departmentMap[cls.departmentName]) {
              departmentMap[cls.departmentName] = 0;
            }
            departmentMap[cls.departmentName] += cls.studentCount || 0;
          });
          labels = Object.keys(departmentMap);
          data = Object.values(departmentMap);
        }
        
        // 创建图表
        const ctx = document.getElementById('gradeDistributionChart').getContext('2d');
        gradeDistributionChart.value = new Chart(ctx, {
          type: 'bar',
          data: {
            labels: labels,
            datasets: [{
              label: '学生人数',
              data: data,
              backgroundColor: [
                'rgba(54, 162, 235, 0.7)',
                'rgba(75, 192, 192, 0.7)',
                'rgba(153, 102, 255, 0.7)',
                'rgba(255, 159, 64, 0.7)',
                'rgba(255, 99, 132, 0.7)',
                'rgba(255, 206, 86, 0.7)'
              ],
              borderColor: [
                'rgba(54, 162, 235, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)',
                'rgba(255, 99, 132, 1)',
                'rgba(255, 206, 86, 1)'
              ],
              borderWidth: 1
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              y: {
                beginAtZero: true,
                title: {
                  display: true,
                  text: '学生人数'
                }
              }
            },
            plugins: {
              legend: {
                position: 'top',
              },
              title: {
                display: true,
                text: '学生分布'
              }
            }
          }
        });
      } catch (error) {
        console.error('初始化年级分布图表失败:', error);
      }
    };
    
    // 初始化班级人数图表
    const initClassSizeChart = async () => {
      try {
        // 获取班级数据
        const classRes = await getClasssList(1, 10, 0, {});
        if (classRes.code !== 200 || !classRes.data.list) return;
        
        const classesData = classRes.data.list;
        
        // 销毁旧图表
        if (classSizeChart.value) {
          classSizeChart.value.destroy();
        }
        
        let labels, data;
        
        if (classChartType.value === 'class') {
          // 按班级
          labels = classesData.map(cls => cls.className);
          data = classesData.map(cls => cls.studentCount || 0);
        } else if (classChartType.value === 'major') {
          // 按专业
          const majorMap = {};
          classesData.forEach(cls => {
            if (!majorMap[cls.majorName]) {
              majorMap[cls.majorName] = { count: 0, classCount: 0 };
            }
            majorMap[cls.majorName].count += cls.studentCount || 0;
            majorMap[cls.majorName].classCount += 1;
          });
          labels = Object.keys(majorMap);
          data = Object.values(majorMap).map(major => major.count / major.classCount);
        } else {
          // 按学院
          const departmentMap = {};
          classesData.forEach(cls => {
            if (!departmentMap[cls.departmentName]) {
              departmentMap[cls.departmentName] = { count: 0, classCount: 0 };
            }
            departmentMap[cls.departmentName].count += cls.studentCount || 0;
            departmentMap[cls.departmentName].classCount += 1;
          });
          labels = Object.keys(departmentMap);
          data = Object.values(departmentMap).map(dept => dept.count / dept.classCount);
        }
        
        // 创建图表
        const ctx = document.getElementById('classSizeChart').getContext('2d');
        classSizeChart.value = new Chart(ctx, {
          type: 'line',
          data: {
            labels: labels,
            datasets: [{
              label: '平均人数',
              data: data,
              fill: true,
              backgroundColor: 'rgba(54, 162, 235, 0.2)',
              borderColor: 'rgba(54, 162, 235, 1)',
              tension: 0.4
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              y: {
                beginAtZero: true,
                title: {
                  display: true,
                  text: '平均人数'
                }
              }
            },
            plugins: {
              legend: {
                position: 'top',
              },
              title: {
                display: true,
                text: '班级人数统计'
              }
            }
          }
        });
      } catch (error) {
        console.error('初始化班级人数图表失败:', error);
      }
    };
    
    // 获取最新学生列表
    const fetchRecentStudents = async (page = 1, size = 10, search = '') => {
      loadingStudents.value = true;
      
      try {
        const response = await getStudentList(
          page, 
          size, 
          0, 
          { studentName: search }
        );
        
        if (response.code === 200) {
          recentStudents.value = response.data.list || [];
          studentTotal.value = response.data.total || 0;
        } else {
          ElMessage.error(response.msg || '获取学生列表失败');
        }
      } catch (error) {
        console.error('获取学生列表错误:', error);
        ElMessage.error('获取学生列表失败，请稍后重试');
      } finally {
        loadingStudents.value = false;
      }
    };
    
    // 获取班级列表
    const fetchClasses = async (page = 1, size = 10, grade = '') => {
      loadingClasses.value = true;
      
      try {
        const response = await getClasssList(
          page, 
          size, 
          0, 
          { grade: grade || undefined }
        );
        
        if (response.code === 200) {
          classes.value = response.data.list || [];
          filteredClasses.value = [...classes.value];
          classTotal.value = response.data.total || 0;
        } else {
          ElMessage.error(response.msg || '获取班级列表失败');
        }
      } catch (error) {
        console.error('获取班级列表错误:', error);
        ElMessage.error('获取班级列表失败，请稍后重试');
      } finally {
        loadingClasses.value = false;
      }
    };
    
    // 刷新所有数据
    const refreshAllData = () => {
      fetchDashboardData();
      fetchRecentStudents();
      fetchClasses();
    };
    
    // 更新图表类型
    const updateGradeChart = () => {
      initGradeDistributionChart();
    };
    
    const updateClassChart = () => {
      initClassSizeChart();
    };
    
    // 搜索学生
    const searchStudents = () => {
      fetchRecentStudents(1, studentPageSize.value, studentSearch.value);
    };
    
    // 筛选班级
    const filterClasses = () => {
      fetchClasses(1, classPageSize.value, classFilter.value);
    };
    
    // 学生分页处理
    const handleStudentSizeChange = (newSize) => {
      studentPageSize.value = newSize;
      fetchRecentStudents(studentCurrentPage.value, newSize, studentSearch.value);
    };
    
    const handleStudentPageChange = (newPage) => {
      studentCurrentPage.value = newPage;
      fetchRecentStudents(newPage, studentPageSize.value, studentSearch.value);
    };
    
    // 班级分页处理
    const handleClassSizeChange = (newSize) => {
      classPageSize.value = newSize;
      fetchClasses(classCurrentPage.value, newSize, classFilter.value);
    };
    
    const handleClassPageChange = (newPage) => {
      classCurrentPage.value = newPage;
      fetchClasses(newPage, classPageSize.value, classFilter.value);
    };
    
    // 查看学生详情
    const viewStudent = (student) => {
      console.log('查看学生详情:', student);
      // 实际项目中应跳转到详情页
    };
    
    // 编辑学生
    const editStudent = (student) => {
      console.log('编辑学生:', student);
      // 实际项目中应打开编辑对话框
    };
    
    // 查看班级详情
    const viewClass = (cls) => {
      console.log('查看班级详情:', cls);
      // 实际项目中应跳转到详情页
    };
    
    // 生命周期钩子
    onMounted(() => {
      // 初始化页面数据
      fetchDashboardData();
      fetchRecentStudents();
      fetchClasses();
      
      // 监听窗口大小变化，重绘图表
      window.addEventListener('resize', () => {
        if (gradeDistributionChart.value) gradeDistributionChart.value.resize();
        if (classSizeChart.value) classSizeChart.value.resize();
      });
    });
    
    return {
      ...icons,
      totalStudents,
      totalTeachers,
      totalClasses,
      totalCourses,
      studentIncrease,
      teacherIncrease,
      classIncrease,
      courseIncrease,
      lastUpdateTime,
      gradeChartType,
      classChartType,
      recentStudents,
      studentCurrentPage,
      studentPageSize,
      studentTotal,
      studentSearch,
      classes,
      filteredClasses,
      classCurrentPage,
      classPageSize,
      classTotal,
      classFilter,
      grades,
      loadingDashboard,
      loadingStudents,
      loadingClasses,
      refreshAllData,
      updateGradeChart,
      updateClassChart,
      searchStudents,
      filterClasses,
      handleStudentSizeChange,
      handleStudentPageChange,
      handleClassSizeChange,
      handleClassPageChange,
      viewStudent,
      editStudent,
      viewClass
    };
  }
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.last-update {
  color: #666;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  height: 180px;
}

.card-header {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 16px;
}

.card-header el-icon {
  margin-right: 10px;
  font-size: 24px;
}

.card-content {
  padding: 20px 0;
  text-align: center;
}

.stat-number {
  font-size: 48px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.stat-change {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  font-size: 14px;
}

.text-green {
  color: #67c23a;
}

.text-red {
  color: #f56c6c;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-content {
  padding: 16px;
}

.tables-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.table-content {
  padding: 16px;
}

.table-content el-pagination {
  margin-top: 16px;
  text-align: right;
}
</style>